<template>
	<view class="TUI-conversation-list" @click="dialogID = ''">
		<view v-for="(item, index) in conversationList" :key="index" >
			<view v-if="!item.isDelete">
			<view class="TUI-conversation-item"  v-if="item.type!='@TIM#SYSTEM' && item.conversationID != 'C2C99999999'"   :class="[
          dialogID === item.conversationID && 'selected',
          item.isPinned && 'pinned']" 
				@click="handleGotoItem(item)" @longpress="handleItemLongpress(item)">
				<aside class="left">
					<img class="avatar" :src="handleItemAvator(item)" />
					<span class="num" v-if="
              item.unreadCount > 0 &&
              item.messageRemindType !== 'AcceptNotNotify'
            ">
						{{ item.unreadCount > 99 ? "99+" : item.unreadCount }}
					</span>
					<span class="num-notNotify" v-if="
              item.unreadCount > 0 &&
              item.messageRemindType === 'AcceptNotNotify'
            "></span>
				</aside>
				<main class="content">
					<header class="content-header">
						<label>
							<p class="name">{{ handleItemName(item) }}</p>
						</label>
					</header>
					<footer class="content-footer">
						<span class="content-footer-unread" v-if="
                item.unreadCount > 0 &&
                item.messageRemindType === 'AcceptNotNotify'
              ">[{{ item.unreadCount > 99 ? "99+" : item.unreadCount }}条]</span>
								<span class="message-text">
								  <span style="color:#f35f5f" v-if="item.conversationID !== store.state.timStore.conversationID && item.groupAtInfoList && item.groupAtInfoList.length > 0">{{ messageAtMeText(item) }}</span>
								  <span v-else v-html="item.retType"></span>
								<!--  <span v-else-if="!item.lastMessage.type" v-html="targetMessages(item)"></span> -->
								</span>	
						<view class="conversation-line"></view>
					</footer> 
					<view class="item-footer">
						<span class="time" v-if="!item.lastMessage.type">{{item.time}}</span>
						<span class="time" v-if="item.lastMessage.type">{{handleItemTime(item.lastMessage.lastTime)}}</span>
						<image class="mute-icon" v-if="item.messageRemindType === 'AcceptNotNotify'"
							src="../../assets/icon/mute.svg"></image>
					</view>
				</main>
				<view class="dialog-box" v-if="item.conversationID === dialogID">
					<view class="conversation-options" @click.stop="handleConversation('delete', dialogID)">{{$t('chat.chat_delete_chat')}}</view>
					<view class="conversation-options" v-if="!item.isPinned"
						@tap.stop="handleConversation('ispinned', dialogID)">{{$t('chat.chat_top')}}</view>
					<view class="conversation-options" v-if="item.isPinned"
						@click.stop="handleConversation('dispinned', dialogID)">{{$t('chat.chat_unpin')}}</view>
		<!-- 			<view class="conversation-options" v-if="
              item.messageRemindType === '' ||
              item.messageRemindType === 'AcceptAndNotify'
            " @click.stop="handleConversation('mute', dialogID)">消息免打扰</view>
					<view class="conversation-options" v-if="item.messageRemindType === 'AcceptNotNotify'"
						@click.stop="handleConversation('notMute', dialogID)">取消免打扰</view> -->
				</view>
			</view>
			</view>
		</view>
	</view>
</template>
<script lang="ts">
	import {
		defineComponent,
		reactive,
		toRefs,
		watchEffect,
		computed,
		getCurrentInstance
	} from "vue";
	import {
		caculateTimeago
	} from "../../utils/date";
	import {
		useI18n
	} from "vue-i18n";
	import{
		onShow,
		onLoad,
	}from "@dcloudio/uni-app";
	import httpInterceptor from '@/utils/http.interceptor.js';
	import store from '../../TUICore/store';
	import { useI18n } from 'vue-i18n';
	import userStore from '@/store/index.js';
	import { useTransitionState } from "vue";
	import { TIM } from "../../debug/tim";
	import timStore from "../../TUICore/store/modules/timStore";
	import state from "../../../../store/state";
	const conversationKey = "tim-conversation_uid:" + userStore.state.vuex_user.uid;
	const TUIConversationList = defineComponent({
		props: {
			conversationList: {
				type: Array,
				default: () => {
					return [];
				},
			},
			currentID: {
				type: String,
				default: () => {
					return "";
				},
			},
		},

		setup(props: any, ctx: any) {
			const that = getCurrentInstance()
			const { t } = useI18n()
			const obj = reactive({
				conversationList: [],
				currentID: "",
				isOpened: "none",
				currentConversation: {},
				dialogID: "",
				tap:"",
				retType: "",
				tar:0,
				tap1:0,
				tarr:"",
				lastmessage: '',
				message:'',
			});
			 onLoad(() => {

				})
			 onShow(()=>{
				props.conversationList.forEach(item =>{
					if (item.lastMessage.type){
						handleItemMessage(item)
					}else{
					 targetMessages(item)
					}
				})
				const readNum = uni.getStorageSync('readNum');
				var sum = 0;
				if(readNum > 0){
					sum = readNum
					if(sum >99){
						sum = 99
					}
					uni.setTabBarBadge({
						index: 2,
						text: readNum
					});							
				}else{
					return uni.removeTabBarBadge({
						index: 2
					});	 
				}
			});
			watchEffect(() => {
				props.conversationList.forEach(item =>{
					if (item.lastMessage.type){
						handleItemMessage(item)
					}else{
					 targetMessages(item)
					}
				})
				obj.conversationList = props.conversationList;
				obj.currentID = props.currentID;
				var sum = 0
				for(var i = 0 ;  i < obj.conversationList.length;i++){		
					if(obj.conversationList[i].unreadCount>0&&obj.conversationList[i].conversationID!='C2C99999999'&&obj.conversationList[i].conversationID!='@TIM#SYSTEM'){
					   	sum+=obj.conversationList[i].unreadCount
					}
				}
				if(sum > 0){
					uni.setTabBarBadge({
						index: 2,
						text: sum
					});			
				}
				// store.commit("timStore/setReadNum",sum);
				uni.setStorageSync("readNum",sum)
				//获取服务器上存储的 iDOCK 会话列表
				// that.proxy.$http.get('/mgr/tim/chat/conversation/data', {}).then(res => {
				// 	if (res.length > 0) {
				// 		console.log("返回的历史消失", res)
				// 		const conversationList = res
				// 		const conversationList = [
				// 			... obj.conversationList,
				// 			...res,
				// 		]
				// 		console.log("新的哦", conversationList)
				// 		obj.conversationList = conversationList
				// 	}
				// });
			});
			//处理带有@功能的最后一条信息数据
			const messageAtMeText = (conversation: any) => {
				let text = ''
				if (conversation.groupAtInfoList.length > 0) {
					 conversation.groupAtInfoList.forEach(item => {
					    if (item.atTypeArray[0] === uni.$TIM.TYPES.CONV_AT_ME) {
					      text.indexOf('[@所有人]') !== -1 ? (text = '[@所有人][有人@我]') : (text ='[' + t('chat.has_at') + ']')
					    }
					    if (item.atTypeArray[0] === uni.$TIM.TYPES.CONV_AT_ALL) {
					      text.indexOf('[有人@我]') !== -1 ? (text = '[有人@我][@所有人]') : (text = '[' + t('chat.at_all') + ']')
					    }
					    if (item.atTypeArray[0] === uni.$TIM.TYPES.CONV_AT_ALL_AT_ME) {
					      text = '[' + t('chat.at_all') + ']'+ '[' + t('chat.has_at') + ']'
					    }
					  })
				 }
				return text
			};
			//处理头像
			const handleItemAvator = (item: any) => {
				let avatar = "";
				switch (item.type) {
					case uni.$TIM.TYPES.CONV_C2C:
						avatar =
							item?.userProfile?.avatar ||
							"https://idock-1305057061.cos.ap-beijing.myqcloud.com/avatar/2021-08-02/avatar.jpg";
						break;
					case uni.$TIM.TYPES.CONV_GROUP:
						avatar =
							item?.groupProfile?.avatar ||
							"https://idock-1305057061.cos.ap-beijing.myqcloud.com/avatar/2021-08-02/avatar.jpg";
						break;
					case uni.$TIM.TYPES.CONV_SYSTEM:
						avatar =
							item?.groupProfile?.avatar ||
							"https://idock-1305057061.cos.ap-beijing.myqcloud.com/avatar/2021-08-02/avatar.jpg";
						break;
				}
				return avatar;
			};
			// 处理昵称
			const handleItemName = (item: any) => {
				let name = "";
				switch (item.type) {
					case uni.$TIM.TYPES.CONV_C2C:
						name = item?.userProfile.nick || item?.userProfile?.userID || "";
						break;
					case uni.$TIM.TYPES.CONV_GROUP:
						name = item.groupProfile.name || item?.groupProfile?.groupID || "";
						break;
					case uni.$TIM.TYPES.CONV_SYSTEM:
						name = "系统通知";
						break;
				}
				return name;
			};
			// 处理时间
			const handleItemTime = (time: number) => {
				if (time > 0) {
					return caculateTimeago(time * 1000, that);
				} 
			};
			 async function targetMessages(message:any){
				await historMessages(message)
			}
			//处理7天前的会话列表最后一条消息
			 function historMessages(item:any){
				 //获取缓存历史消息
				that.proxy.$http.get('/mgr/tim/chat/conversation/data',{}).then(res =>{
					var undelmessage = []
					for(var i in res){
						if(res[i].conversationID===item.conversationID){
							undelmessage=res[i]
						}
					}
					item.time=caculateTimeago(undelmessage.lastMessage.lastTime * 1000, that)
					//判断最后一条消息是否是撤回消息
					if (undelmessage.lastMessage.isRevoked) {
						if (undelmessage.lastMessage.fromAccount == that.proxy.$store.state.vuex_user.uid) {
							item.retType =  t('chat.chat_recall_message_self')
							return ""
						}
						else{
							 item.retType =undelmessage.lastMessage.nick + t('chat.chat_recall_message')
							 return ""
						}
					}
						switch (undelmessage.lastMessage.type) {
								case 'TIMTextElem':
									item.retType = undelmessage.lastMessage.payload.text
									break;
								case 'TIMSoundElem':
								   item.retType  = t('chat.chat_yuyin')
									break;
								case 'TIMImageElem':
								    item.retType  =  t('chat.chat_image')
									break;
								case 'TIMFileElem':
								    item.retType  = t('chat.chat_file')
									break;
								case 'TIMVideoFileElem':
								     item.retType  = t('chat.chat_video')
									break;
								case 'TIMRelayElem':
								     item.retType  = t('chat.chat_merger')
									break;
								case 'TIMFaceElem':
								   item.retType  = t('chat.chat_face')	
								   break;
								case 'TIMCustomElem':
									var tap = JSON.stringify(JSON.parse(JSON.parse(undelmessage.lastMessage.payload.data).data).call_type)
								    if(tap==='1'){
										 item.retType  = t('chat.chat_call')
										break;
									}	
									if(tap==='2'){
										 item.retType  = t('chat.chat_call1')
										break;
									}
									else{
										 item.retType  = t('chat.calling_custom_message')
										break;
									}
								default:
									item.retType  = t('chat.chat_tips1');
									break;
					}				
				})
			};
			// 处理7天内的lastMessage
			async function handleItemMessage(message: any){	
				//判断最后一条消息是否为撤回消息
					if (message.lastMessage.isRevoked) {
						if (message.lastMessage.revoker == that.proxy.$store.state.vuex_user.uid) {
							message.retType =  t('chat.chat_recall_message_self')
							return ""
						}
						if(message.lastMessage.nick===''){
							 message.retType = t('chat.chat_revoke1')
							 return ""
						}
						message.retType = message.lastMessage.nick + t('chat.chat_recall_message')
						return ""
					}
					switch (message.lastMessage.type) {
						case uni.$TIM.TYPES.MSG_TEXT:
							message.retType = message.lastMessage.payload.text;
							break
						case 'TIMSoundElem':
						    message.retType = t('chat.chat_yuyin')
							break
						case 'TIMImageElem':
						    message.retType = t('chat.chat_image')
							break
						case 'TIMFileElem':
						    message.retType = t('chat.chat_file')
							break
						case 'TIMVideoFileElem':
						    message.retType = t('chat.chat_video')
							break
						case 'TIMRelayElem':
						    message.retType = t('chat.chat_merger')
							break
						case 'TIMFaceElem':
						    message.retType = t('chat.chat_face')	
							break
						case 'TIMCustomElem':
							var tap = JSON.stringify(JSON.parse(JSON.parse(message.lastMessage.payload.data).data).call_type)
						    if(tap==='1'){
								message.retType = t('chat.chat_call')
								break
							}	
							if(tap==='2'){
								message.retType = t('chat.chat_call1')
								break
							}
							else{
								message.retType = t('chat.calling_custom_message')
								break
							}
						default:
							message.retType = t('chat.chat_tips1');
							break
					}
					
			};

			const handleGotoItem = (item: any) => {
				console.log("item", item)
				ctx.emit("handleGotoItem", item);
			};

			const handleItemLongpress = (item: any) => {
				obj.currentConversation = item;
				obj.dialogID = item.conversationID;
				if (item.type === "C2C") {
					obj.currentuserID = item.userProfile.userID;
				} else if (item.type === "GROUP") {
					obj.currentuserID = item.groupProfile.groupID;
				}
				obj.conversationType = item.type;
			};
			// todo
			const handlerIsOpened = (item: any) => {
				if (item.conversationID === obj.doalogID) {
					return "right";
				} else {
					return "none";
				}
			};

			// 删除会话,后续TODO,置顶聊天,消息免打扰
			const handleConversation = (type: string) => {
				switch (type) {
					case "delete":
						uni.$TUIKit.TUIConversationServer.deleteConversation(
							obj.dialogID
						).then((imResponse: any) => {
							const {
								conversationID
							} = imResponse.data;
						});
						for(var i in props.conversationList){
							if(obj.dialogID==props.conversationList[i].conversationID){
								props.conversationList[i].isDelete=true
							}
						}
						operateConversationList({
							conversation_id: obj.dialogID,
							is_delete: 1
						});
						obj.dialogID = "";
						break;
					case "ispinned":
						if (type === "ispinned") {
							const options: any = {
								conversationID: obj.dialogID,
								isPinned: true,
								};
							uni.$TUIKit.TUIConversationServer.pinConversation(options).then(
								(imResponse: any) => {
								   }
								);
							operateConversationList({
								conversation_id: obj.dialogID,
								is_pinned: 1
							});
						}
						obj.dialogID = "";
						break;
					case "dispinned":
						if (type === "dispinned") {
							const options: any = {
								conversationID: obj.dialogID,
								isPinned: false,
							};
							uni.$TUIKit.TUIConversationServer.pinConversation(options).then(
								(imResponse: any) => {}
							);
							for(var i in props.conversationList){
								if(obj.dialogID==props.conversationList[i].conversationID){
									props.conversationList[i].isPinned=false
								}
							}
							operateConversationList({
								conversation_id: obj.dialogID,
								is_pinned: 2
							});
						}
						obj.dialogID = "";
						break;
					case "mute":
						if (type === "mute" && obj.conversationType === "C2C") {
							const options: any = {
								userIDList: [obj.currentuserID],
								messageRemindType: uni.$TIM.TYPES.MSG_REMIND_ACPT_NOT_NOTE,
							};
							uni.$TUIKit.TUIConversationServer.muteConversation(options).then(
								(imResponse: any) => {
									console.log(imResponse);
								}
							);
						} else if (type === "mute" && obj.conversationType === "GROUP") {
							const options: any = {
								groupID: obj.currentuserID,
								messageRemindType: uni.$TIM.TYPES.MSG_REMIND_ACPT_NOT_NOTE,
							};
							uni.$TUIKit.TUIConversationServer.muteConversation(options).then(
								(imResponse: any) => {
									console.log(imResponse);
								}
							);
						}
						obj.dialogID = "";
						break;
					case "notMute":
						if (type === "notMute" && obj.conversationType === "C2C") {
							const options: any = {
								userIDList: [obj.currentuserID],
								messageRemindType: uni.$TIM.TYPES.MSG_REMIND_ACPT_AND_NOTE,
							};
							uni.$TUIKit.TUIConversationServer.muteConversation(options).then(
								(imResponse: any) => {
									console.log(imResponse);
								}
							);
						} else if (type === "notMute" && obj.conversationType === "GROUP") {
							const options: any = {
								groupID: obj.currentuserID,
								messageRemindType: uni.$TIM.TYPES.MSG_REMIND_ACPT_AND_NOTE,
							};
							uni.$TUIKit.TUIConversationServer.muteConversation(options).then(
								(imResponse: any) => {
									console.log(imResponse);
								}
							);
						}
						obj.dialogID = "";
						break;
				}

			};
			function operateConversationList(param) {
				that.proxy.$http.post('/mgr/user/chat/message/conversation', param).then((res) => {
					console.log(JSON.stringify(res))
				}).catch(err => {})
				uni.$TUIKit.TUIConversationServer.getConversationList()
			}
			return {
				...toRefs(obj),
				handleGotoItem,
				handleItemAvator,
				handleItemTime,
				handleItemMessage,
				handleItemName,
				handleItemLongpress,
				handleConversation,
				handlerIsOpened,
				store,
				messageAtMeText,
				historMessages,
				targetMessages,
				operateConversationList
			};
		},
	});
	export default TUIConversationList;
</script>
<style lang="scss" scoped>
	.TUI-conversation {
		font-family: PingFangSC-Regular;
		font-weight: 400;
		letter-spacing: 0;
		color: #ffffff;
		&-list {
			list-style: none;
		}

		&-item {
			position: relative;
			padding: 12px;
			display: flex;
			align-items: center;

			.left {
				position: relative;

				.num {
					font-family: PingFangSC-Regular;
					position: absolute;
					display: inline-block;
					right: -6px;
					top: -6px;
					background: red;
					width: 30rpx;
					height: 30rpx;
					font-size: 11px;
					text-align: center;
					line-height: 30rpx;
					border-radius: 30rpx;
					color: #ffffff;
					font-weight: 600;
					letter-spacing: 0;
				}

				.num-notNotify {
					position: absolute;
					display: inline-block;
					right: -4px;
					top: -4px;
					background: red;
					width: 11px;
					height: 11px;
					border-radius: 50%;
					color: #ffffff;
				}

				.avatar {
					width: 48px;
					height: 48px;
					border-radius: 6px;
				}
			}

			.content {
				flex: 1;
				padding-left: 10px;
				position: relative;

				p {
					width: 200px;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
					font-weight: 400;
					font-size: 14px;
					color: #999999;
					letter-spacing: 0;
					line-height: 19px;
					font-family: PingFangSC-Regular;
				}

				.conversation-line {
					position: absolute;
					display: block;
					left: 0;
					right: -12px;
					height: 0.5px;
					transform: scaleY(0.3);
					background: #b0b0b0;
					/* padding-top: 10px; */
					bottom: -15px;
				}

				.name {
					font-weight: 400;
					font-size: 16px;
					color: #000000;
					letter-spacing: 0;
					margin-bottom: 5px;
					font-family: PingFangSC-Regular;
				}

				&-header {
					display: flex;
					justify-content: space-between;
					align-items: center;

					label {
						flex: 1;
						font-size: 14px;
						color: #000000;

						// .name {
						// 	width: 110px;
						// 	overflow: hidden;
						// 	text-overflow: ellipsis;
						// 	white-space: nowrap;
						// }
					}

					.time {
						font-size: 12px;
						color: #b0b0b0;
						line-height: 16px;
						display: inline-block;
						max-width: 75px;
						font-weight: 400;
					}
				}

				&-footer {
					color: #999999;
					line-height: 16px;
					display: flex;

					.message-text {
						margin-left: 4px;
						display: block;
						width: 240px;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
					}
				}

				.item-footer {
					position: absolute;
					right: 0;
					top: 0;
					justify-items: center;
					display: flex;
					flex-direction: column;
					align-items: flex-end;

					.time {
						font-size: 12px;
						color: #b0b0b0;
						line-height: 16px;
						display: inline-block;
						max-width: 75px;
						font-weight: 400;
						margin-bottom: 5px;
					}

					.mute-icon {
						display: block;
						width: 20px;
						height: 20px;
					}
				}
			}

			.dialog-box {
				position: absolute;
				z-index: 5;
				background: #fff;
				border: 1px solid #dddddd;
				padding: 5px 20px;
				right: 15px;
				top: 30px;

				&-item {
					top: 60px;
					right: 40px;
					box-shadow: 0 11px 20px 0 rgb(0 0 0 / 30%);
					background: #ffffff;
					border: 1px solid #e0e0e0;
					box-shadow: 0 -4px 12px 0 rgb(0 0 0 / 6%);
					border-radius: 8px;
				}

				.conversation-options {
					height: 45px;
					font-family: PingFangSC-Regular;
					font-weight: 400;
					font-size: 15px;
					color: #4f4f4f;
					letter-spacing: 0;
					line-height: 45px;
				}
			}
		}
	}

	.selected {
		background: #edf0f5;
	}

	.pinned {
		background: #eef0f3;
	}
</style>
